package org.my.app.config;

import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.my.app.config.generated.LocationPairType;
import org.my.app.config.generated.LocationSynchronizerConfiguration;
import org.my.app.config.generated.ObjectFactory;
import org.my.app.config.generated.SynchronizationUnitType;

public class Configuration {

	public static void main(String args[]) throws JAXBException {
		
		JAXBContext jc = JAXBContext.newInstance("org.my.app.config.generated");
		
		Marshaller m = jc.createMarshaller();
		
		ObjectFactory of = new ObjectFactory();
		LocationSynchronizerConfiguration lsc = 
			of.createLocationSynchronizerConfiguration();
		
		SynchronizationUnitType sut = of.createSynchronizationUnitType();
		
		LocationPairType lpt1 = of.createLocationPairType();
		lpt1.setFixedLocation("fixed location");
		lpt1.setRemoteLocation("remote location");
		lpt1.setLocationName("Location1");
		
		LocationPairType lpt2 = of.createLocationPairType();
		lpt2.setFixedLocation("fixed location2");
		lpt2.setRemoteLocation("remote location2");
		lpt2.setLocationName("Location2");
		
		sut.getLocationPair().add(lpt1);
		sut.getLocationPair().add(lpt2);
		sut.setUnitName("Unit1");
		
		lsc.getSynchronizationUnit().add(sut);
		
		StringWriter sw = new StringWriter();
		
		m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
		m.marshal(lsc, sw);
		
		System.out.println(sw.toString());
		
		/*
		 * 
		 */
		
		Unmarshaller um = jc.createUnmarshaller();
		
		StringReader sr = new StringReader( sw.toString() );
		
		//JAXBElement e = (JAXBElement) 
		
		LocationSynchronizerConfiguration c = 
			(LocationSynchronizerConfiguration) um.unmarshal(sr);
		
		int n = c.getSynchronizationUnit().size();
		for ( int i=0; i<n; i++ )
			System.out.println("Unit: " + i + ", size = " + c.getSynchronizationUnit().get(i).getLocationPair().size());
		
	}
	
}
